package com.demo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserStatusTypeHandler extends BaseTypeHandler<String> {

    private String codeToString(int code) {
        return code == 1 ? "正常" : "禁用";
    }

    private int stringToCode(String str) {
        return str.trim().equals("正常") ? 1 : 0;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
            throws SQLException {
        System.out.println("---将字符串类型变量转换后存入数据表中,列编号:"+i+" 变量值:"+parameter);
        ps.setInt(i, stringToCode(parameter));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);
        System.out.println("---转换ResultSet中名字为"+columnName+"的列,值为"+code);
        return codeToString(code);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        System.out.println("---转换ResultSet中序号为"+columnIndex+"的列,值为"+code);
        return codeToString(code);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        System.out.println("---转换CallableStatement中序号为"+columnIndex+"的列,值为"+code);
        return codeToString(code);
    }
}